<template>
  <div class="recharge-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">充值中心</h2>
      <p class="page-subtitle">管理您的账户余额和充值记录</p>
    </div>

    <!-- 账户信息卡片 -->
    <div class="account-cards">
      <el-card class="account-card" shadow="hover">
        <div class="card-content">
          <div class="card-icon total">
            <el-icon><Wallet /></el-icon>
          </div>
          <div class="card-info">
            <div class="card-label">账户总额</div>
            <div class="card-value">¥{{ allmoney }}</div>
          </div>
        </div>
      </el-card>

      <el-card class="account-card" shadow="hover">
        <div class="card-content">
          <div class="card-icon balance">
            <el-icon><Money /></el-icon>
          </div>
          <div class="card-info">
            <div class="card-label">可用余额</div>
            <div class="card-value">¥{{ money }}</div>
          </div>
        </div>
      </el-card>

      <el-card class="account-card" shadow="hover">
        <div class="card-content">
          <div class="card-icon used">
            <el-icon><ShoppingBag /></el-icon>
          </div>
          <div class="card-info">
            <div class="card-label">已使用</div>
            <div class="card-value">¥{{ usedmoney }}</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 充值申请卡片 -->
    <el-card class="recharge-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <h3 class="card-title">
            <el-icon><CreditCard /></el-icon>
            申请充值
          </h3>
          <div class="recharge-notice">
            <el-icon><InfoFilled /></el-icon>
            <span>充值申请需要管理员审核，审核通过后金额将自动到账</span>
          </div>
        </div>
      </template>

      <div class="recharge-form">
        <div class="amount-section">
          <div class="form-label">充值金额</div>
          <div class="amount-input-group">
            <el-input
              v-model="rechargeAmount"
              placeholder="请输入充值金额"
              type="number"
              :min="1"
              :max="10000"
              class="amount-input"
            >
              <template #prepend>¥</template>
            </el-input>
            <el-button
              type="primary"
              @click="submitRechargeRequest"
              :loading="submitting"
              :disabled="!canSubmit"
            >
              提交申请
            </el-button>
          </div>

          <div class="quick-amounts">
            <el-button
              v-for="amount in quickAmounts"
              :key="amount"
              @click="selectAmount(amount)"
              :class="{ active: rechargeAmount == amount }"
              class="quick-amount-btn"
            >
              ¥{{ amount }}
            </el-button>
          </div>
        </div>

        <div class="payment-section">
          <div class="form-label">支付方式</div>
          <el-radio-group v-model="paymentMethod" class="payment-methods">
            <el-radio-button label="支付宝">
              <el-icon><Money /></el-icon>
              支付宝
            </el-radio-button>
            <el-radio-button label="微信">
              <el-icon><ChatDotRound /></el-icon>
              微信支付
            </el-radio-button>
            <el-radio-button label="银行卡">
              <el-icon><CreditCard /></el-icon>
              银行卡
            </el-radio-button>
          </el-radio-group>
        </div>
      </div>
    </el-card>

    <!-- 标签页 -->
    <el-card class="records-card" shadow="hover">
      <el-tabs v-model="activeTab" class="records-tabs">
        <el-tab-pane label="充值记录" name="history">
          <div class="records-content">
            <el-table :data="rechargeHistory" stripe>
              <el-table-column prop="date" label="日期" width="120" />
              <el-table-column prop="amount" label="金额" width="100">
                <template #default="{ row }">
                  <span class="amount-text">¥{{ row.amount }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="method" label="支付方式" width="120" />
              <el-table-column label="状态" width="100">
                <template #default>
                  <el-tag type="success">已到账</el-tag>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <el-tab-pane label="申请记录" name="requests">
          <div class="records-content">
            <el-table :data="rechargeRequests" stripe>
              <el-table-column prop="request_time" label="申请时间" width="160">
                <template #default="{ row }">
                  {{ formatDateTime(row.request_time) }}
                </template>
              </el-table-column>
              <el-table-column prop="amount" label="申请金额" width="120">
                <template #default="{ row }">
                  <span class="amount-text">¥{{ row.amount }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="payment_method" label="支付方式" width="120" />
              <el-table-column prop="status" label="审核状态" width="120">
                <template #default="{ row }">
                  <el-tag
                    :type="getStatusType(row.status)"
                    :effect="row.status === 'pending' ? 'plain' : 'dark'"
                  >
                    {{ getStatusText(row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="processed_time" label="处理时间" width="160">
                <template #default="{ row }">
                  {{ row.processed_time ? formatDateTime(row.processed_time) : '-' }}
                </template>
              </el-table-column>
              <el-table-column prop="admin_comment" label="管理员备注" min-width="150">
                <template #default="{ row }">
                  {{ row.admin_comment || '-' }}
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { ElMessage } from 'element-plus';
import {
  rechargeApi,
  getUserRechargeApi,
  calculateTotalAmountApi,
  calculateBalanceApi,
  getRechargeAmountApi,
  createRechargeRequestApi,
  getUserRechargeRequestsApi
} from "@/utils/api";
import {
  Wallet,
  Money,
  ShoppingBag,
  CreditCard,
  InfoFilled,
  ChatDotRound
} from '@element-plus/icons-vue';

// 响应式数据
const money = ref(0);
const usedmoney = ref(0);
const allmoney = ref(0);
const paymentMethod = ref("");
const rechargeHistory = ref([]);
const rechargeRequests = ref([]);
const rechargeAmount = ref("");
const activeTab = ref("history");
const submitting = ref(false);

// 快速充值金额选项
const quickAmounts = [10, 50, 100, 200, 500, 1000];

// 获取用户信息
const user_id = JSON.parse(localStorage.getItem("user")).user_id;

// 计算属性
const canSubmit = computed(() => {
  return rechargeAmount.value > 0 && paymentMethod.value && !submitting.value;
});

// 初始化账户信息
const init = async () => {
  try {
    const [totalRes, balanceRes, amountRes] = await Promise.all([
      calculateTotalAmountApi({ user_id }),
      calculateBalanceApi({ user_id }),
      getRechargeAmountApi({ user_id })
    ]);

    money.value = parseFloat(totalRes.data || 0).toFixed(2);
    usedmoney.value = parseFloat(balanceRes.data || 0).toFixed(2);
    allmoney.value = parseFloat(amountRes.data || 0).toFixed(2);
  } catch (error) {
    console.error('获取账户信息失败:', error);
    ElMessage.error('获取账户信息失败');
  }
};

// 获取充值记录
const fetchRechargeHistory = async () => {
  try {
    const res = await getUserRechargeApi({ user_id });
    rechargeHistory.value = res.data || [];
  } catch (error) {
    console.error('获取充值记录失败:', error);
  }
};

// 获取充值申请记录
const fetchRechargeRequests = async () => {
  try {
    const res = await getUserRechargeRequestsApi({ user_id });
    rechargeRequests.value = res.data || [];
  } catch (error) {
    console.error('获取充值申请记录失败:', error);
  }
};

// 提交充值申请
const submitRechargeRequest = async () => {
  if (!canSubmit.value) {
    ElMessage.warning('请填写完整的充值信息');
    return;
  }

  const amount = parseFloat(rechargeAmount.value);
  if (amount <= 0) {
    ElMessage.warning('充值金额必须大于0');
    return;
  }

  if (amount > 10000) {
    ElMessage.warning('单次充值金额不能超过10000元');
    return;
  }

  try {
    submitting.value = true;

    const res = await createRechargeRequestApi({
      user_id,
      amount,
      payment_method: paymentMethod.value
    });

    if (res.code === 200) {
      ElMessage.success('充值申请提交成功，请等待管理员审核');

      // 清空表单
      rechargeAmount.value = "";
      paymentMethod.value = "";

      // 刷新申请记录
      await fetchRechargeRequests();
    } else {
      ElMessage.error(res.message || '充值申请提交失败');
    }
  } catch (error) {
    console.error('提交充值申请失败:', error);
    ElMessage.error('充值申请提交失败，请重试');
  } finally {
    submitting.value = false;
  }
};

// 选择快速充值金额
const selectAmount = (amount) => {
  rechargeAmount.value = amount.toString();
};

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    'pending': 'warning',
    'approved': 'success',
    'rejected': 'danger'
  };
  return statusMap[status] || 'info';
};

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'pending': '待审核',
    'approved': '已通过',
    'rejected': '已拒绝'
  };
  return statusMap[status] || status;
};

// 格式化日期时间
const formatDateTime = (dateStr) => {
  if (!dateStr) return '-';
  return new Date(dateStr).toLocaleString('zh-CN');
};

// 组件挂载时初始化数据
onMounted(async () => {
  await init();
  await fetchRechargeHistory();
  await fetchRechargeRequests();
});
</script>

<style lang="less" scoped>
.recharge-page {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.page-header {
  margin-bottom: 24px;

  .page-title {
    font-size: 24px;
    font-weight: 600;
    color: #303133;
    margin: 0 0 8px 0;
  }

  .page-subtitle {
    color: #909399;
    margin: 0;
    font-size: 14px;
  }
}

.account-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.account-card {
  border: none;
  border-radius: 12px;
  overflow: hidden;

  :deep(.el-card__body) {
    padding: 24px;
  }

  .card-content {
    display: flex;
    align-items: center;
    gap: 16px;
  }

  .card-icon {
    width: 60px;
    height: 60px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;
    color: white;

    &.total {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    }

    &.balance {
      background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
    }

    &.used {
      background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
    }
  }

  .card-info {
    flex: 1;

    .card-label {
      font-size: 14px;
      color: #909399;
      margin-bottom: 8px;
    }

    .card-value {
      font-size: 28px;
      font-weight: 600;
      color: #303133;
    }
  }
}

.recharge-card, .records-card {
  border: none;
  border-radius: 12px;
  overflow: hidden;
  margin-bottom: 24px;

  :deep(.el-card__header) {
    padding: 24px;
    background: #fafbfc;
    border-bottom: 1px solid #ebeef5;
  }

  :deep(.el-card__body) {
    padding: 24px;
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;

  .card-title {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 18px;
    font-weight: 600;
    color: #303133;
    margin: 0;

    .el-icon {
      color: #409eff;
    }
  }

  .recharge-notice {
    display: flex;
    align-items: center;
    gap: 6px;
    color: #e6a23c;
    font-size: 14px;

    .el-icon {
      font-size: 16px;
    }
  }
}

.recharge-form {
  .form-label {
    font-size: 16px;
    font-weight: 500;
    color: #303133;
    margin-bottom: 12px;
  }
}

.amount-section {
  margin-bottom: 32px;

  .amount-input-group {
    display: flex;
    gap: 16px;
    margin-bottom: 16px;

    .amount-input {
      flex: 1;
      max-width: 300px;
    }
  }

  .quick-amounts {
    display: flex;
    gap: 12px;
    flex-wrap: wrap;

    .quick-amount-btn {
      border-radius: 20px;

      &.active {
        background: #409eff;
        color: white;
        border-color: #409eff;
      }
    }
  }
}

.payment-section {
  .payment-methods {
    display: flex;
    gap: 12px;
    flex-wrap: wrap;

    :deep(.el-radio-button__inner) {
      display: flex;
      align-items: center;
      gap: 6px;
      padding: 12px 20px;
      border-radius: 8px;
    }
  }
}

.records-tabs {
  :deep(.el-tabs__header) {
    margin-bottom: 20px;
  }

  :deep(.el-tabs__item) {
    font-size: 16px;
    font-weight: 500;
  }
}

.records-content {
  .amount-text {
    font-weight: 600;
    color: #f56c6c;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .recharge-page {
    padding: 16px;
  }

  .account-cards {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .card-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .amount-input-group {
    flex-direction: column;

    .amount-input {
      max-width: none;
    }
  }

  .payment-methods {
    flex-direction: column;

    :deep(.el-radio-button) {
      width: 100%;
    }
  }

  .recharge-card, .records-card {
    :deep(.el-card__header) {
      padding: 20px;
    }

    :deep(.el-card__body) {
      padding: 20px;
    }
  }
}
</style>
